const usermodel = require('../model/user.js')
const md5 = require('../model/md5')
const User = require('../schema/user.js').User;
const formidable = require('koa-formidable')
const path = require("path");
const fs = require("fs");
const { uploadFile } = require('../util/upload')
const reg = async (ctx) => {
  
    await ctx.render('reg', {
        "active": "注册" || '',
        "title": "注册" || '',
        'nowurl':ctx.request.query.nowurl,
        
        "keywords":"顶上前端,ariza全栈,",
        "description":"追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰",
    })
}
//检查
const checkLogin = async (ctx) => {
    let userid = {
        username:  ctx.session.username
    }
    if (ctx.session.username) {
        await usermodel.findalluser(userid).then(function (doc) {

            ctx.body = {
                status: 200,
                message: '',
                result: {
                    userName:ctx.session.username || '',
                    avatar: doc.avatar
                }
            };

        })

    } else {

        ctx.body = {
            status: -1,
            message: '未登录',
            result: ''
        };
    }
};

const doreg = async (ctx) => {

    let datauser={username: ctx.request.body.username}

    let user = new User({
        username: ctx.request.body.username,
        email:ctx.request.body.email,
        password: md5(md5(ctx.request.body.password) + "wei"),
        avatar: "/img/default.jpg"
    })
    let doc = await usermodel.findalluser(datauser);
    if (doc) {
        ctx.body = "-1";
    }else if(ctx.request.body.username==''){
    		ctx.body = "-2";
    } else {
        await new Promise((resolve, reject) => {
            user.save((err) => {
                if (err) {
                    reject(err);
                }
                resolve();
            });
        });
        ctx.body = "1"
        ctx.session.login = "1";
        ctx.session.username = user.username;
        ctx.session.avatar=user.avatar
    }
}
const login = async (ctx) => {
    let user = new User({
        username: ctx.request.body.username,
        password: md5(md5(ctx.request.body.password) + "wei"),
    })

    let datauser={username: ctx.request.body.username};
    let doc = await usermodel.findalluser(datauser);
    if (!doc) {
        ctx.body = "-1";
    } else if (user.password == doc.password) {
 
        ctx.session.login = '1';
        ctx.session.avatar=doc.avatar
        ctx.session.username = user.username;
        ctx.body = "1"
    } else {
        ctx.body = '-2'
    }
}
const logout = async (ctx) => {
    ctx.session.login = "333"
    ctx.session.avatar=""
    ctx.body ={
        status:200
    }
  
    
}




const uploadheader = async (ctx) => {
    if (ctx.session.login != "1") {
        ctx.body = "非法闯入，这个页面要求登陆！";
        return;
    }
    // 上传文件请求处理
    let result = { success: false }
    let serverFilePath = path.join(__dirname, '../public')
    // 上传文件事件
    result = await uploadFile(ctx, {
        fileType: 'album',
        path: serverFilePath
    })
 
  let conditions = { "username": ctx.session.username };
    let update = { $set: { "avatar": result.data.pictureUrl } };

    let doc = await usermodel.updateava(conditions, update)

    if (doc) {
        ctx.body = result;
        ctx.session.avatar=result.data.pictureUrl
       // ctx.redirect('/list')
    }
}


module.exports = {
    reg,
    doreg,
    login,
    logout,
    checkLogin,
    uploadheader
}